class MpButton extends HTMLElement {
  static get observedAttributes() {
    return [
      "disabled",
      "isbusy",
      "isbusytext",
      "buttonstyle",
      "size",
      "iconleft",
      "text",
      "iconright",
    ];
  }

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.render();
  }

  attributeChangedCallback(name, oldValue, newValue) {
    this.render();
  }

  render() {
    const disabled = this.hasAttribute("disabled");
    const isBusy = this.hasAttribute("isbusy");
    const isBusyText = this.getAttribute("isbusytext");
    let buttonStyle = this.getAttribute("buttonstyle") || "brand";
    let size = this.getAttribute("size") || "medium";
    const iconLeft = this.getAttribute("iconleft");
    const text = this.getAttribute("text");
    const iconRight = this.getAttribute("iconright");

    buttonStyle = "button-style-" + buttonStyle;
    size = "button-size-" + size;

    let currentClassName =
      text === undefined
        ? `${buttonStyle} ${size} icon-only`
        : `${buttonStyle} ${size}`;

    const styles = `
          <link rel="stylesheet" href="./src/mp-design-tokens/components-styles/Button.css">
          <link rel="stylesheet" href="./src/mp-design-tokens/components-styles/Overlay.css">
        `;

    const busyContent = isBusy
      ? `
            <div class="button-box">
              <mp-icon class="button-is-busy" icon="refresh"></mp-icon>
              ${isBusyText !== undefined ? `<span style="padding-top: var(--mp-spacing-2);">${isBusyText}</span>` : ""}
            </div>
          `
      : "";

    const normalContent = `
          <div class="overlay"></div>
          <div class="button-box">
            ${iconLeft ? `<mp-icon icon="${iconLeft}"></mp-icon>` : ""}
            ${text ? `<span style="padding-top: var(--mp-spacing-2);">${text}</span>` : ""}
            ${iconRight ? `<mp-icon icon="${iconRight}"></mp-icon>` : ""}
          </div>
        `;

    // Проверяем, есть ли иконка справа, если нет - не отображаем кнопку
    const buttonContent = iconLeft || text || iconRight ? normalContent : "";

    this.shadowRoot.innerHTML = `
          ${styles}
          <button type="button" class="button ${currentClassName}" ${disabled || isBusy ? "disabled" : ""}>
            ${isBusy ? busyContent : buttonContent}
          </button>
        `;
  }
}

customElements.define("mp-button", MpButton);
